package com.hengtian.roastwall.service.impl;

import com.hengtian.roastwall.entity.LoginUser;
import com.hengtian.roastwall.entity.User;
import com.hengtian.roastwall.entity.dto.RegisterDto;
import com.hengtian.roastwall.mapper.UserMapper;
import com.hengtian.roastwall.service.UserService;
import com.hengtian.roastwall.utils.JwtUtil;
import com.hengtian.roastwall.utils.RedisCache;
import com.hengtian.roastwall.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public User getUserInfo(String userName) {
        User userInfo = userMapper.getUserInfo(userName);
        return userInfo;
    }

    @Override
    public ResponseResult login(User user) {
        // 使用AuthenticationManager进行认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 如果没有通过认证
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登陆失败");

        }

        // 如果通过认证，使用userID生成一个jwt存入ResponseResult
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userid = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userid);
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        // 将数据存入Redis中
        redisCache.setCacheObject("login:" + userid, loginUser);
        return new ResponseResult(200, "登录成功", map);

    }

    @Override
    public ResponseResult logout() {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userid = loginUser.getUser().getId().toString();
        redisCache.deleteObject("login:" + userid);
        return new ResponseResult(200, "注销成功");
    }

    @Override
    public List<String> getAuthorities(User user) {
        List<String> authorities = userMapper.getAuthorities(user);
        return authorities;
    }

    @Override
    public List<User> getAllUsers() {
        List<User> users = userMapper.getAllUsers();
        return users;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void addUser(User user) {
        userMapper.addUser(user);
    }

    @Override
    public User register(RegisterDto dto) {
        User user = userMapper.getUserByUserName(dto.getUserName());
        // 用户已存在
        if (user != null) {
            return user;
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(dto.getPassword());
        dto.setPassword(encode);
        // 用户不存在
        userMapper.registerUser(dto);
        return user;
    }

    @Override
    public int updateAvatarById(User user) {

        int count = userMapper.updateById(user);
        return count;
    }


}
